import { Component, loader } from "cc";
import useStore from "../store";
import { flux } from './flux'

const URL_LIST = {
  development: 'https://test-api.bendiclass.com',
  production: 'https://api.bendiclass.com'
}

const url_http = "https://test-api.bendiclass.com";

export default class HttpUtil {
  /**
  * 请求协议的方法
  * @param path 请求接口的路径
  * @param params 参数
  * @param callBack 回调函数
  */

  public static get(path, params) {
    const that = this
    return new Promise(function (resolve, reject) {
      // try
      var requestUrl = url_http + path;
      var xhr = loader.getXMLHttpRequest();
      // var data=self.paramData(params);
      var data = params;
      let param = '?';
      for (var key in data) {
        var paramStr = key + "=" + data[key];
        if (param == "") {
          param += paramStr;
        } else {
          param += "&" + paramStr;
        }
      }

      xhr.open("GET", requestUrl + param);
      xhr.timeout = 5000;
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
      xhr.setRequestHeader("token", `${useStore().userStore.token}`);

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status == 200) {
          var respone = xhr.responseText;
          const httpData = that.dataFactory(respone)
          resolve(httpData);
        }
      };

      xhr.onerror = function () {
        reject('err');
      };

      xhr.send();
    })

  }

  public static post(url, param: object = {}) {
    const that = this
    return new Promise(function (resolve, reject) {
      url = url_http + url;
      var xhr = loader.getXMLHttpRequest();
      let dataStr = '';
      Object.keys(param).forEach(key => {
        dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
      })
      if (dataStr !== '') {
        dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
      }
      xhr.open("POST", url, true);
      // 第一种表单提交  
      // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      // 第二种  json提交
      xhr.setRequestHeader("Content-Type", "application/JSON");
      xhr.setRequestHeader("token", `${useStore().userStore.token}`);

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          let respone = xhr.responseText;
          if (xhr.status >= 200 && xhr.status < 300) {
            respone = xhr.responseText;
            const httpData = that.dataFactory(respone)
            resolve(httpData);

          } else {
            reject(respone)
          }
        }
      };
      // 第一种表单提交 和上面配合使用 
      // xhr.send(JSON.stringify(dataStr));
      //  第二种  json提交  和上面配合使用
      xhr.send(JSON.stringify(param));
    })
  }

  public static dataFactory (res) {
    let httpData = res
    if (typeof httpData === 'string') {
      httpData = JSON.parse(httpData)
    }
    // console.log(httpData, 'httpData')
    if (httpData.errCode === 0) {
      return httpData.data
    } else if (httpData.errCode === 600 || httpData.errCode === 603 || httpData.errCode === 602) {
      return this.redirectJump(res)
    }
  }

  public static redirectJump (res) {
    console.error('【token 过期：】', res.response.data.errCode, res.response.data.message)
  }

}

function ccclass(arg0: string) {
  throw new Error("Function not implemented.");
}
